package com.bestv.utils.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * 重新加载
 * User: Henry
 * Date: 14-5-20
 */
public abstract class Reloadable extends Thread {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private String configFile;
    private int reloadInterval = 3600; // one hour by default
    private long configFileModifyTime = 0;

    @Override
    public void run() {
        while (true) {
            File configure = new File(configFile);
            if (!configure.exists()) {
                logger.error(String.format("[BMM] configuration file %s is not exist", configure.getName()));
                return;
            }

            if (configure.lastModified() != configFileModifyTime) {
                logger.info(String.format("[BMM] configuration file %s is reloading ...", configure.getName()));
                reload();
                configFileModifyTime = configure.lastModified();
            }

            try {
                logger.info(String.format("[BMM] configuration file %s will be reloaded in %s seconds later.", configure.getName(), reloadInterval));
                sleep(reloadInterval * 1000);
            } catch (InterruptedException e) {
                logger.error("The thread is interrupted.", e);
            }
        }
    }

    protected abstract void reload();

    public void setConfigFile(String configFile) {
        this.configFile = configFile;
    }

    public String getConfigFile() {
        return configFile;
    }

    public void setReloadInterval(int reloadInterval) {
        this.reloadInterval = reloadInterval;
    }
}
